<script>
import FileService from '@/request/file/File'
export default {
  name: 'AdminComponentsUpload',
  data () {
    return {
      imageUrl: ''
    }
  },
  created () {},
  methods: {
    handleUploadImage (options) {
      return new Promise((resolve, reject) => {
        FileService.uploadImage(options.file, options.onProgress).then(res => {
          resolve(res)
        }).catch(error => {
          this.$message.error(error || '上传图片失败!')
          reject(error)
        })
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview (file) {
      console.log(file)
    }
  }
}
</script>

<template>
  <el-main>
    <el-scrollbar class="default-scrollbar" wrap-class="default-scrollbar__wrap" view-class="p20-scrollbar__view">
      <h2 class="title">用户头像上传</h2>
      <div class="avater-wrap">
        <el-upload
          class="avatar-uploader"
          action="upload"
          :show-file-list="false"
          :http-request="handleUploadImage"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <h2 class="title">照片墙</h2>
      <div class="wall-wrap">
        <el-upload
          action="upload"
          list-type="picture-card"
          :http-request="handleUploadImage"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
    </el-scrollbar>
  </el-main>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title {
  line-height: 60px;
}
.avater-wrap {
  width: 180px;
  height: 180px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
